import { computed } from 'vue'
import { defineStore, acceptHMRUpdate } from 'pinia'
import { useLocalStorage } from '@vueuse/core'
import { userApi } from '@/api'
import { useRequest } from '@/hooks/request'

export const useUserStore = defineStore('user', () => {
  const user = ref(null)
  const token = useLocalStorage('token', '')
  const { execute } = useRequest(userApi.getUser)

  const setUser = info => (user.value = info)
  const getUser = async () => await execute()
  const getAndSetUser = async () => {
    const userInfo = await getUser()
    user.value = userInfo
  }

  const setToken = val => {
    token.value = val
  }

  const clear = () => {
    setUser(null)
    setToken('')
  }

  return {
    token,
    user,
    roleId: computed(() => user.value?.roleId),
    isLogined: computed(() => !!token.value),
    getUser,
    setUser,
    getAndSetUser,
    setToken,
    clear
  }
})

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useUserStore, import.meta.hot))
}
